package com.example.stock.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.stock.business.TradingRankSatBusiness;
import com.example.stock.controller.dto.DailyDetailDTO;
import com.example.stock.model.DailyDetail;
import com.example.stock.service.DailyDataService;
import com.example.stock.service.IndustryDataService;
import com.example.stock.service.RankService;
import com.example.stock.util.DataUtil;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@CrossOrigin(origins = "*")
@RequestMapping("rank")
@RestController
public class TradingRankController {

    @Autowired
    IndustryDataService industryDataService;

    @Autowired
    DailyDataService  dailyDataService;

    @GetMapping("lt5")
    public Result lt5() {
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("gt5")
    public Result gt5(@RequestParam(required = false) String date) {

        List<DailyDetail> tradingRank;
        if (date == null) {
            tradingRank = dailyDataService.getLastedDailyDataByDate();
        } else {
            tradingRank = dailyDataService.getDailyDataByDate(date);
        }

        List<DailyDetail> list = tradingRank.stream()
                .filter(i -> i.getPct() >= 5)
                .limit(300)
                .toList();

        Map<String, Object> ret = new HashMap<>();
        ret.put("date", dailyDataService.getDates());
        ret.put("data", list);

        return ResultGenerator.genSuccessResult(ret);
    }

    @Autowired
    TradingRankSatBusiness tradingRankSatBusiness;

    @GetMapping("sat/{year}")
    public Result index(@PathVariable String year) {
        return ResultGenerator.genSuccessResult(tradingRankSatBusiness.getTradingRankSat(year));
    }

    @GetMapping("industry/{industry}")
    public Result industry(@PathVariable("industry") String industry) {
        return ResultGenerator.genSuccessResult(format(industryDataService.getStocksByTag(industry)));
    }

    @GetMapping("multiStock")
    public Result multiStock(@RequestParam("stocks") String stocks, @RequestParam(defaultValue = "200") int count) {
        String[] stockSplit = stocks.split(DataUtil.STOCK_SPLIT);
        return ResultGenerator.genSuccessResult(format(List.of(stockSplit), count));
    }

    private Map<String, List<DailyDetailDTO>> format(List<String> stocks) {
        return format(stocks, 200);
    }

    private Map<String, List<DailyDetailDTO>> format(List<String> stocks, int count) {
        Map<String, List<DailyDetailDTO>> tradingRanks = dailyDataService.getDailyDataByStocks(stocks);

        // 限制返回个数
        Map<String, List<DailyDetailDTO>> ret = new LinkedHashMap<>();
        stocks.forEach(stock ->{
            List<DailyDetailDTO> list = tradingRanks.get(stock);
            ret.put(stock, CollUtil.sub(list, -1 * count, list.size()));
        });

        return ret;
    }

    @GetMapping("detail")
    public Result detail(@RequestParam(required = false) String date) {
        List<DailyDetail> tradingRanks;
        if (date == null) {
            tradingRanks = dailyDataService.getLastedDailyDataByDate();
        } else {
            tradingRanks = dailyDataService.getDailyDataByDate(date);
        }

        return ResultGenerator.genSuccessResult(tradingRanks);
    }

    @GetMapping("lpNewHigh/{date}")
    public Result lpNewHigh(@PathVariable String date) {

        List<DailyDetail> tradingRanks = dailyDataService.getDailyDataByDate(date);
        if (tradingRanks == null || tradingRanks.isEmpty()) {
            return ResultGenerator.genSuccessResult(null);
        }

        Map<String, List<DailyDetail>> ret = new LinkedHashMap<>();

        tradingRanks.stream().filter(i -> i.getLp() >= 99)  // 当前分位点高于 99
                .sorted(Comparator.comparing(DailyDetail::getPct).reversed()) // 按涨跌排序
                .forEach(i -> {

            List<DailyDetailDTO> tradingRankByStock = dailyDataService.getDailyData(i.getStock());

            // 往前 70 天，往后 20 天
            List<DailyDetailDTO> lastItems = tradingRankByStock.stream()
                    .sorted(Comparator.comparing(DailyDetail::getDate).reversed())
                    .filter(item -> item.getDate().compareTo(date) <= 0).limit(70)
                    .toList();

            // 找出前一天分位点小于 99
            if (lastItems.get(1).getLp() > 99) {
                return;
            }

            List<DailyDetailDTO> firstItems = tradingRankByStock.stream()
                    .sorted(Comparator.comparing(DailyDetail::getDate))
                    .filter(item -> item.getDate().compareTo(date) > 0).limit(20)
                    .toList();

            ret.put(i.getStock(), Stream.concat(firstItems.stream(), lastItems.stream())
                    .sorted(Comparator.comparing(DailyDetail::getDate).reversed())
                    .collect(Collectors.toList()));
        });

        return ResultGenerator.genSuccessResult(ret);
    }

    @Autowired
    RankService rankService;

    @GetMapping("update/{stock}")
    Result upRank(@PathVariable String stock) {
        rankService.updateRankByStock(stock);
        return ResultGenerator.genSuccessResult();
    }
}